package com.umeox.ota.gloable;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.abupdate.iot_libs.OtaAgentPolicy;
import com.abupdate.iot_libs.data.constant.BroadcastConsts;
import com.abupdate.iot_libs.data.constant.SDKConfig;
import com.abupdate.iot_libs.engine.thread.Dispatcher;
import com.umeox.ota.data.constant.Constant;
import com.umeox.ota.data.db.ClientDb;
import com.umeox.ota.data.local.FotaConfig;
import com.umeox.ota.data.local.Installation;
import com.umeox.ota.data.repository.base.IRepository;
import com.umeox.ota.data.repository.base.RepositoryComponent;
import com.umeox.ota.engine.FotaInitTask;
import com.umeox.ota.engine.NewVersionDispatcher;
import com.umeox.ota.receiver.OtaReceiver;
import com.umeox.ota.receiver.UsbDiskReceiver;
import com.umeox.ota.utils.Utils;


/**
 * @author fighter_lee
 * @date 2017/5/11
 */

public class App extends BaseApp {

    public static Context sCx;

    @Override
    public void onCreate() {
        init();
        registerFOTANotify();
        super.onCreate();

    }

    protected void init() {
        sCx = getApplicationContext();
        Installation.init();
        SDKConfig.setIsTest(false);
        String filePath = Utils.isSupportAbupdate() ? Constant.OTA_PACKAGE_PATH : getFilesDir().getAbsolutePath() + "/update.zip";
        FotaConfig.getInstance().setDownloadPath(filePath);
        FotaInitTask.initStart(this);
        //重要：设置初始化开始标志，需要初始化完成，才能使用FOTA的接口
        Dispatcher.getDispatcher().enqueue(new FotaInitTask(this));

    }


    protected void registerFOTANotify() {
        OtaReceiver otaReceiver = new OtaReceiver();
        UsbDiskReceiver usbDiskReceiver = new UsbDiskReceiver();
        // TODO: 2019/12/18 本地升级功能打开的情况下才需要监听 ACTION_MEDIA_UNMOUNTED & ACTION_MEDIA_MOUNTED 广播
        registerReceiver(usbDiskReceiver, new IntentFilter(Intent.ACTION_MEDIA_UNMOUNTED));
        registerReceiver(usbDiskReceiver, new IntentFilter(Intent.ACTION_MEDIA_MOUNTED));

        registerReceiver(otaReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        //升级结果广播
        LocalBroadcastManager.getInstance(this).registerReceiver(otaReceiver, new IntentFilter(BroadcastConsts.ACTION_FOTA_UPDATE_RESULT));
        //升级推送广播
        LocalBroadcastManager.getInstance(this).registerReceiver(otaReceiver, new IntentFilter(BroadcastConsts.ACTION_FOTA_NOTIFY));
        //收到新版本通知
        OtaAgentPolicy.setNewVersionListener(NewVersionDispatcher::onReceiverNewVersion);
    }

    @Override
    public RepositoryComponent getRepositoryComponent() {
        return ((IRepository) mAppDelegate).getRepositoryComponent();
    }

    public ClientDb getDB() {
        return getRepositoryComponent().repositoryManager().obtainRoomDatabase(ClientDb.class, ClientDb.DB_NAME);
    }
}
